Page({
  data: {
    orderList: [{
        id: 0,
        name: '工商银行'
      },
      {
        id: 1,
        name: '建设银行'
      },
      {
        id: 2,
        name: '邮储银行'
      },
      {
        id: 3,
        name: '邮储闪光卡'
      },
      {
        id: 4,
        name: '邮储胖虎卡'
      },
      {
        id: 5,
        name: '中国银行'
      },
      {
        id: 6,
        name: '建行生活'
      },
      {
        id: 7,
        name: '农业银行'
      },
      {
        id: 8,
        name: '云闪付活动'
      },
      {
        id: 9,
        name: '微信活动'
      },
      {
        id: 10,
        name: '支付宝活动'
      }
    ],
    order: [{
      id: 0,
      orderListId: 0,
      money: 22,
      minMoney: 22.01,
      content: '路径：11-11-22，尽快',
      startTime: 1791616530000,
      endTime: 1791616530000,
      stateID: 0
    }],
    state: [{
        id: 0,
        stateName: '待领取'
      },
      {
        id: 1,
        stateName: '生效中'
      },
      {
        id: 2,
        stateName: '已使用'
      },
      {
        id: 3,
        stateName: '已过期'
      }
    ],
    inputOrderListId: '', // 输入的订单ID
    inputMoney: '', // 输入的金额
    inputMinMoney: '', // 输入的最小金额
    inputContent: '', // 输入的内容
    selectedStateID: 0 // 选择的状态ID
  },

  onLoad: function () {
    const savedOrders = wx.getStorageSync('orders') || [];
    this.setData({
      orders: savedOrders
    });
  },

  bindPickerChange: function (e) {
    this.setData({
      selectedIndex: e.detail.value
    });
  },

  bindStartDateChange: function (e) {
    this.setData({
      startDate: e.detail.value,
      endDate: e.detail.value
    });
  },

  bindEndDateChange: function (e) {
    this.setData({
      endDate: e.detail.value
    });
  },

  formSubmit: function (e) {
    const formData = e.detail.value;
    const now = new Date();
    const startTime = new Date(this.data.startDate);
    const endTime = new Date(this.data.endDate);

    let stateID = 2; // 默认为已使用
    if (endTime < now) {
      stateID = 3; // 已过期
    } else if (startTime > now) {
      stateID = 0; // 待领取
    } else {
      stateID = 1; // 生效中
    }

    const newOrder = {
      id: Date.now(),
      orderListId: this.data.orderList[this.data.selectedIndex].id,
      money: formData.money,
      minMoneny: formData.minMoney,
      content: formData.content,
      startTime: this.data.startDate,
      endTime: this.data.endDate,
      stateID: stateID
    };

    let orders = this.data.orders;
    orders.push(newOrder);
    this.setData({
      orders: orders
    });

    wx.setStorageSync('orders', orders);
  }
});